﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存盘点新增</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
        }

        .container {
            padding: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }

        .card {
            background: #fff;
            border-radius: 6px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .card-header {
            padding: 16px 20px;
            border-bottom: 1px solid #e8e8e8;
            background: #fafafa;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

            .card-header h3 {
                margin: 0;
                font-size: 16px;
                font-weight: 600;
                color: #333;
            }

        .card-body {
            padding: 20px;
        }

        .el-form .el-row {
            display: flex;
            flex-wrap: wrap;
        }

        .el-form .el-col {
            display: flex;
            flex-direction: column;
        }

        .form-section .el-form-item__content {
            position: relative;
        }

        .form-section .el-select,
        .form-section .el-date-editor {
            width: 100%;
        }

        .form-section .el-date-editor--datetime {
            width: 100%;
        }

        .form-section .el-input__inner {
            padding-right: 30px;
        }

        .form-section .el-date-editor .el-input__prefix {
            left: auto;
            right: 5px;
        }

        /* 统一日期框长度 */
        .el-date-editor.el-input, .el-date-editor.el-input__inner {
            width: 100%;
        }

        .table-operations {
            margin-bottom: 16px;
            display: flex;
            gap: 10px;
            align-items: center;
        }

            .table-operations .el-button {
                padding: 8px 15px;
                font-size: 14px;
                height: 36px;
                border-radius: 4px;
            }

            .table-operations .el-button--success {
                background-color: #00b42a;
                border-color: #00b42a;
                color: #fff;
            }

                .table-operations .el-button--success:hover {
                    background-color: #00a824;
                    border-color: #00a824;
                }

            .table-operations .el-button--default {
                background-color: #fff;
                border-color: #ddd;
                color: #333;
            }

                .table-operations .el-button--default:hover {
                    background-color: #f5f5f5;
                    border-color: #ccc;
                }

        .warning-text {
            color: #ff7d00;
            font-size: 14px;
            padding: 6px 12px;
            background-color: #fff8e6;
            border-radius: 4px;
            margin-left: auto;
            display: flex;
            align-items: center;
        }

            .warning-text:before {
                content: "!";
                display: inline-block;
                width: 16px;
                height: 16px;
                background-color: #ff7d00;
                color: white;
                border-radius: 50%;
                text-align: center;
                line-height: 16px;
                font-size: 12px;
                margin-right: 5px;
            }

        .el-table {
            width: 100%;
            margin-bottom: 10px;
            border: 1px solid #e8e8e8;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            background-color: #fafafa;
            font-weight: bold;
            border-top: 1px solid #e4e7ed;
            border-bottom: 1px solid #e4e7ed;
            flex-wrap: wrap;
            gap: 20px;
        }

            .total-row > div {
                min-width: 120px;
                text-align: center;
            }

                .total-row > div:first-child {
                    min-width: 55px;
                    text-align: left;
                }

            .total-row .total-value {
                color: #ff7d00;
            }

        .footer-actions {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #fff;
            padding: 15px 20px;
            border-top: 1px solid #e8e8e8;
            box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }

        .btn-container {
            text-align: right;
            max-width: 1400px;
            margin: 0 auto;
        }

            .btn-container .el-button {
                padding: 10px 20px;
                font-size: 14px;
                border-radius: 4px;
                margin-left: 10px;
            }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .warehouse-warning {
            color: #ff7d00;
            font-size: 14px;
            padding: 6px 12px;
            background-color: #fff8e6;
            border-radius: 4px;
            display: flex;
            align-items: center;
        }

            .warehouse-warning .link-btn {
                color: #409eff;
                margin-left: 5px;
                cursor: pointer;
            }

        .user-selected {
            background-color: #f0f9eb;
        }

        .new-row {
            background-color: #fff8e6;
        }

        .el-pagination {
            margin-top: 10px;
            text-align: right;
        }

        .el-pagination__total {
            color: #666;
        }

        .search-container {
            display: flex;
            justify-content: space-between;
            margin-bottom: 16px;
            align-items: center;
        }

        .text-success {
            color: #00b42a;
        }

        .text-danger {
            color: #f56c6c;
        }

        .debug-info {
            background: #f8f8f8;
            padding: 10px;
            border-radius: 4px;
            margin-top: 10px;
            font-size: 12px;
            color: #666;
        }

        .operator-more-btn {
            cursor: pointer;
            color: #409eff;
            padding: 0 5px;
        }

        /* 库存调拨页面特有的样式调整 */
        .el-form-item__label {
            color: #333;
            font-weight: 500;
        }

        .el-input__inner, .el-textarea__inner {
            border-radius: 4px;
        }

        .el-table .el-table__header th {
            background-color: #f5f7fa;
            color: #333;
            font-weight: 600;
        }

        .el-table .el-table__row:hover td {
            background-color: #f5f7fa;
        }

        .el-tag {
            border-radius: 4px;
        }

        .el-dialog__header {
            padding: 15px 20px;
            border-bottom: 1px solid #e8e8e8;
            background: #fafafa;
        }

        .el-dialog__title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }

        .el-upload {
            width: auto !important;
        }

        .el-upload-dragger {
            width: auto !important;
        }

        /* 上传附件文本靠左 */
        .upload-container {
            text-align: left !important;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            ;
        }

        .el-upload__text {
            text-align: left !important;
            margin-top: 8px;
            color: #666;
            display: block;
        }

        /* 自定义字段标题布局 */
        .custom-field-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
        }

        /* 用户选择模态框高度限制和布局调整 */
        .user-dialog-content {
            max-height: 500px;
            overflow: auto;
        }

        /* 经办人模态框布局调整 */
        .user-dialog-layout {
            display: flex;
            height: 350px; /* 固定模态框内布局高度，根据需求调整 */
            gap: 10px;
            padding: 5px;
        }

        .department-panel, .user-list-panel, .selected-users-panel {
            display: flex;
            flex-direction: column;
            overflow: hidden; /* 子元素超出时隐藏滚动 */
        }

        .user-list-panel, .department-panel {
            flex: 0 0 30%; /* 部门和用户列表面板固定宽度 */
        }

        .selected-users-panel {
            flex: 1; /* 已选用户面板自适应剩余宽度 */
        }

        /* 用户列表区域的滚动容器 */
        .user-list-panel .el-table {
            flex: 1; /* 表格占满面板剩余高度 */
            overflow-y: auto; /* 表格内容超出时垂直滚动 */
        }

        /* 部门树区域的滚动容器 */
        .department-panel .el-tree {
            flex: 1; /* 部门树占满面板剩余高度 */
            overflow-y: auto; /* 部门树内容超出时垂直滚动 */
        }

        /* 已选用户标签区域的滚动容器 */
        .selected-users-panel > div:nth-child(2) {
            flex: 1; /* 标签容器占满面板剩余高度 */
            overflow-y: auto; /* 标签超出时垂直滚动 */
        }
    </style>
</head>
<body>
    <div id="app" class="container">
        <!-- 基础信息表单 -->
        <div class="card">
            <div class="card-header">
                <h3>基础信息</h3>
                <div class="warehouse-warning" v-if="showWarehouseWarning">
                    <el-icon><warning /></el-icon>
                    <span>该仓库暂未锁定，请锁定后再进行盘点</span>
                    <span class="link-btn" @@click="handleGoLockWarehouse">去锁定</span>
                </div>
            </div>
            <div class="card-body">
                <el-form ref="basicForm" :model="formData" :rules="basicRules" label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="盘点单号" prop="inventoryOrderNo">
                                <el-input v-model="formData.inventoryOrderNo" placeholder="自动获取系统编号" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="盘点类型" prop="inventoryType">
                                <el-select v-model="formData.inventoryType" placeholder="请选择" clearable>
                                    <el-option v-for="item in inventoryTypeList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="盘点开始时间" prop="inventoryStartTime">
                                <el-date-picker v-model="formData.inventoryStartTime"
                                                type="datetime"
                                                placeholder="请选择开始时间"
                                                value-format="YYYY-MM-DD HH:mm:ss"
                                                format="YYYY-MM-DD HH:mm:ss"
                                                style="width: 100%">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="盘点结束时间" prop="inventoryEndTime">
                                <el-date-picker v-model="formData.inventoryEndTime"
                                                type="datetime"
                                                placeholder="请选择结束时间"
                                                value-format="YYYY-MM-DD HH:mm:ss"
                                                format="YYYY-MM-DD HH:mm:ss"
                                                style="width: 100%">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="仓库名称" prop="warehouseId">
                                <el-select v-model="formData.warehouseId" placeholder="请选择" clearable @@change="handleWarehouseChange">
                                    <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                                <el-button type="text" size="small" @@click="handleGoAddWarehouse" style="padding: 0; color: #67c23a; font-size: 12px; margin-left: 5px;">设置</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经办人" prop="operatorBy">
                                <el-input v-model="operatorName" placeholder="请选择经办人" readonly>
                                    <template #suffix><span class="operator-more-btn" @@click="showUserDialog">...</span></template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="备注" prop="auditorComment">
                                <el-input v-model="formData.auditorComment" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>

        <!-- 盘点明细表 -->
        <div class="card">
            <div class="card-header">
                <h3>盘点明细</h3>
            </div>
            <div class="card-body">
                <div class="table-operations">
                    <el-button type="success" @@click="handleAddItem">添加</el-button>
                    <el-button type="default" @@click="handleDeleteSelected" :disabled="selectedRows.length === 0">移除</el-button>
                    <el-button type="default" @@click="handleImport">导入</el-button>
                    <div class="warning-text" v-if="showSelectWarehouseTip">请选择仓库!</div>
                    <div class="warning-text" v-if="showSelectGoodsTip">请选择货品!</div>
                </div>
                <div style="overflow-x: auto;">
                    <el-table :data="inventoryItems" border ref="inventoryTable" @@selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
                        <el-table-column prop="index" label="序号" width="60" type="index" fixed="left"></el-table-column>
                        <el-table-column prop="goodsName" label="货品名称" width="140" fixed="left"></el-table-column>
                        <el-table-column prop="goodsCode" label="货品编号" width="120" fixed="left"></el-table-column>
                        <el-table-column prop="specification" label="规格型号" width="120"></el-table-column>
                        <el-table-column prop="goodsType" label="货品类型" width="100"></el-table-column>
                        <el-table-column prop="bookInventory" label="账面库存" width="100">
                            <template #default="scope">{{ formatQuantity(scope.row.bookInventory) }}</template>
                        </el-table-column>
                        <el-table-column label="账面金额" width="100">
                            <template #default="scope">
                                {{ calculateBookAmount(scope.row).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="storageLocationId" label="盘点库位" width="120">
                            <template #default="scope">
                                <el-select v-model="scope.row.storageLocationId"
                                           placeholder="请选择"
                                @@change="handleLocationChange(scope.$index, scope.row)"
                                           :loading="scope.row.updatingBookInventory">
                                    <el-option v-for="loc in locationList"
                                               :key="loc.id"
                                               :label="loc.name"
                                               :value="loc.id"></el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="inventoryQuantity" label="* 盘点数量" width="110">
                            <template #default="scope">
                                <el-input v-model="scope.row.inventoryQuantity" @@change="calculateDiff(scope.$index)" placeholder="必填"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="profitLossQuantity" label="盈亏数量" width="100">
                            <template #default="scope">
                                <span :class="scope.row.profitLossQuantity > 0 ? 'text-success' : scope.row.profitLossQuantity < 0 ? 'text-danger' : ''">
                                    {{ formatQuantity(scope.row.profitLossQuantity) }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="盘点状态" width="100">
                            <template #default="scope">
                                <el-tag :type="getProfitLossType(scope.row.profitLossQuantity)">
                                    {{ getProfitLossText(scope.row.profitLossQuantity) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="referenceUnitPrice" label="* 参考单价" width="100">
                            <template #default="scope">
                                <el-input v-model.number="scope.row.referenceUnitPrice" @@change="calculateProfitLossAmount(scope.$index)" placeholder="必填"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="profitLossAmount" label="盈亏金额" width="100">
                            <template #default="scope">
                                <span :class="scope.row.profitLossAmount > 0 ? 'text-success' : scope.row.profitLossAmount < 0 ? 'text-danger' : ''">
                                    {{ scope.row.profitLossAmount.toFixed(2) }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="remarks" label="备注" width="150">
                            <template #default="scope"><el-input v-model="scope.row.remarks" placeholder="请输入备注"></el-input></template>
                        </el-table-column>
                        <el-table-column label="操作" width="80" fixed="right">
                            <template #default="scope">
                                <el-button type="text" size="small" class="text-danger" @@click="handleRemoveItem(scope.$index)">移除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 调试信息 -->
                <div class="debug-info" v-if="debugMode">
                    <div>选中的行数: {{ selectedRows.length }}</div>
                    <div>盘点明细数量: {{ inventoryItems.length }}</div>
                    <div>选中的货品: {{ selectedRows.map(r => r.goodsName).join(', ') }}</div>
                </div>

                <!-- 合计行 -->
                <div class="total-row">
                    <div>合计</div>
                    <div>账面库存: <span class="total-value">{{ formatTotalQuantity(total.bookInventory) }}</span></div>
                    <div>账面金额: <span class="total-value">{{ total.bookAmount.toFixed(2) }}</span></div>
                    <div>盘点数量: <span class="total-value">{{ formatTotalQuantity(total.inventoryQuantity) }}</span></div>
                    <div>盘盈数量: <span class="total-value">{{ formatTotalQuantity(total.profitQuantity) }}</span></div>
                    <div>盘亏数量: <span class="total-value">{{ formatTotalQuantity(total.lossQuantity) }}</span></div>
                    <div>盘盈金额: <span class="total-value">{{ total.profitAmount.toFixed(2) }}</span></div>
                    <div>盘亏金额: <span class="total-value">{{ total.lossAmount.toFixed(2) }}</span></div>
                </div>
            </div>
        </div>

        <!-- 附件上传 -->
        <div class="card">
            <div class="card-header">
                <h3>上传附件</h3>
            </div>
            <div class="card-body">
                <div class="upload-container">
                    <el-upload ref="upload" v-model:file-list="fileList" action="" :auto-upload="false" :on-change="handleFileChange" :limit="5" accept=".doc,.docx,.pdf,.rar,.zip,.txt" list-type="text">
                        <el-button type="primary" :loading="uploadLoading">上传</el-button>
                        <div class="el-upload__text">您可以上传doc、pdf、rar等格式的文件，单个文件最大200MB</div>
                    </el-upload>
                </div>
            </div>
        </div>

        <!-- 自定义字段 -->
        <div class="card">
            <div class="card-header">
                <div class="custom-field-header">
                    <h3>自定义字段</h3>
                    <el-button type="text" @@click="showCustomFieldSetting">去设置</el-button>
                </div>
            </div>
            <div class="card-body">
                <el-row :gutter="20">
                    <el-col :span="12"><el-form-item label="自定义字段1"><el-input v-model="customFields.field1" placeholder="请输入"></el-input></el-form-item></el-col>
                    <el-col :span="12"><el-form-item label="自定义字段2"><el-input v-model="customFields.field2" placeholder="请输入"></el-input></el-form-item></el-col>
                    <el-col :span="12"><el-form-item label="自定义字段3"><el-input v-model="customFields.field3" placeholder="请输入"></el-input></el-form-item></el-col>
                    <el-col :span="12"><el-form-item label="自定义字段4"><el-input v-model="customFields.field4" placeholder="请输入"></el-input></el-form-item></el-col>
                    <el-col :span="24"><el-form-item label="自定义字段5"><el-input v-model="customFields.field5" type="textarea" rows="3" placeholder="请输入"></el-input></el-form-item></el-col>
                </el-row>
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="footer-actions">
            <div class="btn-container">
                <el-button @@click="handleClose" :loading="buttonLoading.close">关闭</el-button>
                <el-button type="success" @@click="handleSaveAsDraft" :loading="buttonLoading.saveAsDraft">保存为草稿</el-button>
                <el-button type="primary" @@click="handleSave" :loading="buttonLoading.save">保存</el-button>
            </div>
        </div>

        <!-- 部门用户选择模态框 -->
        <el-dialog v-model="userDialogVisible" title="选择人员" width="800px" class="user-dialog">
            <div class="user-dialog-content">
                <div class="user-dialog-layout">
                    <div class="department-panel">
                        <el-input placeholder="请搜索机构" v-model="deptSearch" style="margin-bottom: 10px;">
                            <template #append><el-button icon="el-icon-search" type="text"></el-button></template>
                        </el-input>
                        <el-tree ref="departmentTreeRef" :data="departmentTree" :props="departmentProps" node-key="id" highlight-current @@node-click="handleDepartmentClick" :default-expand-all="true" :filter-node-method="filterDept"></el-tree>
                    </div>
                    <div class="user-list-panel">
                        <el-input placeholder="请搜索用户" v-model="userSearch" style="margin-bottom: 10px;">
                            <template #append><el-button icon="el-icon-search" type="text"></el-button></template>
                        </el-input>
                        <el-table :data="filteredUserList" height="100%" @@row-click="handleUserSelect" :row-class-name="userRowClass" border>
                            <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                            <el-table-column prop="position" label="职位" width="150"></el-table-column>
                            <el-table-column prop="department" label="部门"></el-table-column>
                        </el-table>
                    </div>
                    <div class="selected-users-panel">
                        <div style="font-weight: 500; color: #333; margin-bottom: 10px; padding-bottom: 5px; border-bottom: 1px solid #eee;">已选择 {{ selectedUsers.length }} 人</div>
                        <div style="flex: 1; overflow-y: auto; display: flex; flex-wrap: gap; padding: 0 5px; gap: 8px;">
                            <el-tag v-for="user in selectedUsers" :key="user.id" closable @@close="removeSelectedUser(user)" type="success">{{ user.name }}</el-tag>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>
                <el-button @@click="userDialogVisible = false">取消</el-button>
                <el-button type="primary" @@click="confirmUserSelection">确定</el-button>
            </template>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog v-model="importDialogVisible" title="导入盘点明细" width="500px" @@closed="handleImportDialogClosed">
            <div style="text-align: center; padding: 30px 0;">
                <el-upload ref="importUpload"
                           :auto-upload="false"
                           :on-change="handleImportFileChange"
                           :file-list="importFileList"
                           :show-file-list="true"
                           accept=".xls,.xlsx">
                    <el-button type="primary" size="large">
                        <el-icon><Upload /></el-icon> 选择Excel文件
                    </el-button>
                    <template #tip>
                        <div style="margin-top: 20px; color: #666;">
                            <p>支持.xls和.xlsx格式文件，文件大小不超过2MB</p>
                            <el-button type="text" @@click="downloadTemplate">下载导入模板</el-button>
                        </div>
                    </template>
                </el-upload>

                <!-- 显示选中的文件 -->
                <div v-if="importFileList.length > 0" style="margin-top: 15px;">
                    <el-tag type="success">已选择: {{ importFileList[0].name }}</el-tag>
                </div>
            </div>
            <template #footer>
                <el-button @@click="importDialogVisible = false">取消</el-button>
                <el-button type="primary" @@click="submitImport" :loading="importLoading">确定导入</el-button>
            </template>
        </el-dialog>

        <!-- 添加货品模态框 -->
        <el-dialog v-model="addGoodsDialogVisible" title="添加货品" width="800px">
            <div class="search-container">
                <el-input placeholder="请输入货品编号/名称" v-model="goodsSearch" style="width: 280px;" clearable></el-input>
                <div>
                    <el-button type="default" @@click="resetGoodsSearch" style="margin-right: 10px;">重置</el-button>
                    <el-button type="primary" @@click="searchGoods">查询</el-button>
                </div>
            </div>
            <el-table :data="filteredGoodsList" border @@selection-change="handleGoodsSelectionChange" :row-class-name="tableRowClassName" v-loading="loadingGoods">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="index" label="序号" width="60" type="index"></el-table-column>
                <el-table-column prop="goodsCode" label="货品编号" width="140">
                    <template #default="scope"><span style="color: #ff4d4f;" v-if="scope.row.isNew">*</span>{{ scope.row.goodsCode }}</template>
                </el-table-column>
                <el-table-column prop="goodsName" label="货品名称" width="180"></el-table-column>
                <el-table-column prop="specification" label="规格型号" width="140"></el-table-column>
                <el-table-column prop="unitPrice" label="入库单价" width="120" align="right">
                    <template #default="scope">{{ Number(scope.row.unitPrice).toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="availableQty" label="当前库存" width="120" align="right"></el-table-column>
                <el-table-column prop="storageLocationName" label="库位" width="120"></el-table-column>
            </el-table>

            <div style="margin-top: 12px; display: flex; justify-content: space-between; align-items: center;">
                <div class="el-pagination__total">共 {{ filteredGoodsList.length }} 条</div>
                <el-pagination layout="prev, pager, next, jumper" :total="filteredGoodsList.length" :page-size="10" :current-page="currentPage" @@current-change="handlePageChange"></el-pagination>
            </div>

            <template #footer>
                <el-button @@click="addGoodsDialogVisible = false">取消</el-button>
                <el-button type="primary" @@click="confirmAddGoods">确定</el-button>
            </template>
        </el-dialog>

        <!-- 草稿提示模态框 -->
        <el-dialog v-model="showDraftDialog"
                   title="检测到草稿数据"
                   width="400px"
                   :close-on-click-modal="false"
                   :show-close="false">
            <div style="padding: 20px 0; text-align: center;">
                <p>系统检测到您有未完成的草稿数据，是否加载？</p>
                <p style="color: #666; font-size: 12px; margin-top: 10px;">
                    草稿保存时间：{{ draftSaveTime }}
                </p>
            </div>
            <template #footer>
                <el-button @@click="handleDiscardDraft">取消</el-button>
                <el-button type="primary" @@click="handleLoadDraft">加载草稿</el-button>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, reactive, onMounted, toRaw, computed, watch, nextTick } = Vue;
        const { ElMessage, ElMessageBox, ElLoading, ElIcon, Warning, Calendar, Plus, Delete, Upload } = ElementPlus;

        createApp({
            components: { ElIcon, Warning, Calendar, Plus, Delete, Upload },
            setup() {
                // 基础变量
                const formData = reactive({
                    inventoryOrderId: 0, inventoryOrderNo: '', inventoryType: '',
                    inventoryStartTime: '', inventoryEndTime: '', warehouseId: null,
                    operatorBy: null, sourceOrderNo: '', inbound: 'N', outbound: 'N',
                    orderStatus: '0', auditorComment: '', createBy: 1, createTime: '',
                    updateBy: 1, updateTime: ''
                });
                const operatorName = ref('');
                const showWarehouseWarning = ref(true);
                const showSelectWarehouseTip = ref(false);
                const showSelectGoodsTip = ref(false);
                const customFields = reactive({ field1: '', field2: '', field3: '', field4: '', field5: '' });
                const fileList = ref([]);
                const uploadLoading = ref(false);
                const inventoryTypeList = ref([]);
                const warehouseList = ref([]);
                const locationList = ref([]);
                const userList = ref([]);
                const selectedRows = ref([]);
                const inventoryItems = ref([]);
                const userDialogVisible = ref(false);
                const departmentTree = ref([]);
                const departmentProps = ref({ children: 'children', label: 'name' });
                const selectedDepartment = ref(null);
                const basicForm = ref(null);
                const inventoryTable = ref(null);
                const departmentTreeRef = ref(null);
                const buttonLoading = reactive({ close: false, save: false, saveAsDraft: false });
                const basicRules = {
                    inventoryType: [{ required: true, message: '请选择盘点类型', trigger: ['blur', 'change'] }],
                    warehouseId: [{ required: true, message: '请选择仓库', trigger: ['blur', 'change'] }],
                    operatorBy: [{ required: true, message: '请选择经办人', trigger: ['blur', 'change'] }],
                    inventoryStartTime: [{ required: true, message: '请选择开始时间', trigger: ['blur', 'change'] }]
                };

                // 导入相关变量
                const importDialogVisible = ref(false);
                const importLoading = ref(false);
                const importUpload = ref(null);
                const importFileList = ref([]);
                const importHeaders = ref({
                    'X-Requested-With': 'XMLHttpRequest'
                });
                const importData = ref({ warehouseId: '' });

                // 添加货品模态框变量
                const addGoodsDialogVisible = ref(false);
                const goodsSearch = ref('');
                const selectableGoodsList = ref([]);
                const selectedGoodsList = ref([]);
                const currentPage = ref(1);
                const selectedLocationId = ref(null);
                const loadingGoods = ref(false);
                const isAddGoodsDialogOpen = ref(false);

                // 调试模式
                const debugMode = ref(true);

                // 草稿相关变量
                const showDraftDialog = ref(false);
                const draftSaveTime = ref('');

                // 过滤后的商品列表
                const filteredGoodsList = computed(() => {
                    if (!goodsSearch.value) return selectableGoodsList.value;
                    const search = goodsSearch.value.toLowerCase();
                    return selectableGoodsList.value.filter(item =>
                        item.goodsCode.toLowerCase().includes(search) ||
                        item.goodsName.toLowerCase().includes(search)
                    );
                });

                // 合计数据计算
                const total = computed(() => {
                    let bookInventory = 0, bookAmount = 0, inventoryQuantity = 0;
                    let profitQuantity = 0, lossQuantity = 0, profitAmount = 0, lossAmount = 0;
                    inventoryItems.value.forEach(item => {
                        bookInventory += Number(item.bookInventory) || 0;
                        bookAmount += (Number(item.bookInventory) || 0) * (Number(item.referenceUnitPrice) || 0);
                        inventoryQuantity += Number(item.inventoryQuantity) || 0;

                        if (item.profitLossQuantity > 0) {
                            profitQuantity += item.profitLossQuantity;
                            profitAmount += item.profitLossQuantity * (Number(item.referenceUnitPrice) || 0);
                        } else if (item.profitLossQuantity < 0) {
                            lossQuantity += Math.abs(item.profitLossQuantity);
                            lossAmount += Math.abs(item.profitLossQuantity) * (Number(item.referenceUnitPrice) || 0);
                        }
                    });
                    return {
                        bookInventory, bookAmount, inventoryQuantity,
                        profitQuantity, lossQuantity,
                        profitAmount, lossAmount
                    };
                });

                // 选择变化处理方法
                const handleSelectionChange = (selection) => {
                    console.log('选择变化:', selection);
                    selectedRows.value = selection;
                };

                // 单个移除方法
                const handleRemoveItem = (index) => {
                    console.log('移除单个项目，索引:', index);
                    if (index >= 0 && index < inventoryItems.value.length) {
                        const itemToRemove = inventoryItems.value[index];
                        inventoryItems.value.splice(index, 1);
                        ElMessage.success(`已移除货品: ${itemToRemove.goodsName}`);
                    } else {
                        ElMessage.error('移除失败：索引无效');
                    }
                };

                // 批量移除方法
                const handleDeleteSelected = () => {
                    console.log('批量移除，选中的行:', selectedRows.value);

                    if (selectedRows.value.length === 0) {
                        console.log('没有选中任何行，显示提示');
                        showSelectGoodsTip.value = true;
                        setTimeout(() => {
                            showSelectGoodsTip.value = false;
                        }, 3000);
                        ElMessage.warning('请先选择要移除的货品');
                        return;
                    }

                    ElMessageBox.confirm(
                        `确定要移除选中的 ${selectedRows.value.length} 条记录吗？`,
                        '确认移除',
                        {
                            type: 'warning',
                            confirmButtonText: '确定',
                            cancelButtonText: '取消'
                        }
                    ).then(() => {
                        console.log('用户确认移除');

                        // 获取要移除的货品编号
                        const idsToRemove = selectedRows.value.map(row => row.goodsCode);
                        console.log('要移除的货品编号:', idsToRemove);

                        // 过滤掉选中的行
                        const originalLength = inventoryItems.value.length;
                        inventoryItems.value = inventoryItems.value.filter(item =>
                            !idsToRemove.includes(item.goodsCode)
                        );

                        const removedCount = originalLength - inventoryItems.value.length;
                        console.log(`移除了 ${removedCount} 条记录`);

                        // 清空选中状态
                        selectedRows.value = [];

                        if (removedCount > 0) {
                            ElMessage.success(`成功移除 ${removedCount} 条记录`);
                        } else {
                            ElMessage.warning('未找到匹配的记录进行移除');
                        }
                    }).catch(() => {
                        console.log('用户取消移除');
                    });
                };

                // 生成盘点单号
                const generateInventoryNo = async () => {
                    try {
                        const res = await axios.get('/WhStockTake/GetInventoryNo');
                        formData.inventoryOrderNo = res.data.code === 200 ? res.data.data : 'PD' + new Date().getTime();
                    } catch (error) {
                        formData.inventoryOrderNo = 'PD' + new Date().getTime();
                        ElMessage.error('获取盘点单号异常，使用临时单号');
                    }
                };

                // 加载字典数据
                const loadDictData = async () => {
                    try {
                        const res = await axios.get('/WhStockTake/GetInventoryTypes');
                        inventoryTypeList.value = res.data.data || [];
                    } catch (error) {
                        ElMessage.error(`字典数据加载异常：${error.message}`);
                    }
                };

                // 按部门加载用户
                const loadUsersByDepartment = async (departmentId) => {
                    try {
                        const res = await axios.get(`/WhStockTake/GetUsersByDepartment?departmentId=${departmentId}`);
                        userList.value = res.data.data || [];
                    } catch (error) {
                        ElMessage.error(`加载用户数据异常：${error.message}`);
                    }
                };

                // 加载基础数据
                const loadBasicData = async () => {
                    try {
                        const res = await axios.get('/WhStockTake/GetWarehouseList');
                        warehouseList.value = res.data.data || [];
                        await generateInventoryNo();
                    } catch (error) {
                        ElMessage.error(`基础数据加载异常：${error.message}`);
                    }
                };

                // 检查仓库锁定状态
                const checkWarehouseLockStatus = async (warehouseId) => {
                    if (!warehouseId) { showWarehouseWarning.value = true; return; }
                    try {
                        const res = await axios.get(`/WhStockTake/CheckWarehouseLock?warehouseId=${warehouseId}`);
                        showWarehouseWarning.value = !res.data.data;
                    } catch (error) {
                        showWarehouseWarning.value = true;
                        ElMessage.error(`检查仓库状态异常：${error.message}`);
                    }
                };

                // 初始化表单（含草稿检测）
                const initForm = async () => {
                    try {
                        const localDraft = localStorage.getItem('inventoryDraft');
                        if (localDraft) {
                            const draft = JSON.parse(localDraft);
                            draftSaveTime.value = draft.saveTime || '未知时间';
                            showDraftDialog.value = true;
                            return;
                        }

                        // 修复日期初始化 - 使用简单的日期字符串格式
                        const now = new Date();
                        const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);

                        // 使用简单的日期时间格式
                        const formatSimpleDateTime = (date) => {
                            const year = date.getFullYear();
                            const month = String(date.getMonth() + 1).padStart(2, '0');
                            const day = String(date.getDate()).padStart(2, '0');
                            const hours = String(date.getHours()).padStart(2, '0');
                            const minutes = String(date.getMinutes()).padStart(2, '0');
                            const seconds = String(date.getSeconds()).padStart(2, '0');
                            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                        };

                        formData.inventoryStartTime = formatSimpleDateTime(now);
                        formData.inventoryEndTime = formatSimpleDateTime(tomorrow);

                        await checkWarehouseLockStatus(formData.warehouseId);
                    } catch (error) {
                        console.error('初始化表单失败:', error);
                        showWarehouseWarning.value = true;
                    }
                };

                // 加载草稿数据
                const handleLoadDraft = async () => {
                    showDraftDialog.value = false;
                    const localDraft = localStorage.getItem('inventoryDraft');
                    if (localDraft) {
                        const draft = JSON.parse(localDraft);
                        Object.assign(formData, draft.formData);
                        Object.assign(customFields, draft.customFields);
                        inventoryItems.value = draft.inventoryItems || [];
                        fileList.value = draft.fileList || [];
                        if (formData.warehouseId) await checkWarehouseLockStatus(formData.warehouseId);
                        ElMessage.success(`已加载草稿（保存时间：${draft.saveTime}）`);
                    }
                };

                // 取消加载草稿
                const handleDiscardDraft = async () => {
                    showDraftDialog.value = false;
                    const now = new Date();
                    formData.inventoryStartTime = now.toISOString().slice(0, 19);
                    formData.inventoryEndTime = new Date(now.getTime() + 24 * 60 * 60 * 1000)
                        .toISOString().slice(0, 19);
                    await checkWarehouseLockStatus(formData.warehouseId);
                    ElMessage.info('未加载草稿，将使用新表单');
                };

                // 仓库变更处理
                const handleWarehouseChange = async (warehouseId) => {
                    if (!warehouseId) {
                        locationList.value = [];
                        showWarehouseWarning.value = true;
                        // 清空盘点明细
                        inventoryItems.value = [];
                        return;
                    }

                    // 切换仓库时，清空已添加的盘点明细
                    inventoryItems.value = [];

                    try {
                        await checkWarehouseLockStatus(warehouseId);
                        const res = await axios.get(`/WhStockTake/GetWarehouseLocations?warehouseId=${warehouseId}`);
                        locationList.value = res.data.data || [];

                        // 如果有库位，默认选择第一个
                        if (locationList.value.length > 0) {
                            selectedLocationId.value = locationList.value[0].id;
                        }

                        // 如果添加商品对话框打开，重新加载商品
                        if (isAddGoodsDialogOpen.value && locationList.value.length > 0) {
                            searchGoods();
                        }
                    } catch (error) {
                        ElMessage.error(`仓库数据加载异常：${error.message}`);
                    }
                };

                // 计算盈亏数量（确保数字类型）
                const calculateDiff = (index) => {
                    const item = inventoryItems.value[index];
                    if (item) {
                        // 确保转换为数字类型
                        const inventoryQty = Number(item.inventoryQuantity) || 0;
                        const bookQty = Number(item.bookInventory) || 0;

                        item.profitLossQuantity = inventoryQty - bookQty;
                        item.inventoryQuantity = inventoryQty; // 同步更新为数字类型

                        // 重新计算盈亏金额
                        calculateProfitLossAmount(index);

                        console.log(`计算盈亏: 行${index}, 盘点${inventoryQty}, 账面${bookQty}, 盈亏${item.profitLossQuantity}`);
                    }
                };

                // 计算盈亏金额
                const calculateProfitLossAmount = (index) => {
                    const item = inventoryItems.value[index];
                    if (item) {
                        const profitLossQty = Number(item.profitLossQuantity) || 0;
                        const unitPrice = Number(item.referenceUnitPrice) || 0;
                        item.profitLossAmount = profitLossQty * unitPrice;
                    }
                };

                // 计算账面金额
                const calculateBookAmount = (row) => {
                    const bookQty = Number(row.bookInventory) || 0;
                    const unitPrice = Number(row.referenceUnitPrice) || 0;
                    return bookQty * unitPrice;
                };
                // 格式化数量
                const formatQuantity = (quantity) => Number(quantity) || 0;
                // 格式化合计数量
                const formatTotalQuantity = (quantity) => Number(quantity) || 0;
                // 获取盈亏类型
                const getProfitLossType = (quantity) => quantity > 0 ? 'success' : quantity < 0 ? 'danger' : 'info';
                // 获取盈亏文本
                const getProfitLossText = (quantity) => quantity > 0 ? '盘盈' : quantity < 0 ? '盘亏' : '正常';

                // 导入处理
                const handleImport = () => {
                    console.log('=== 导入按钮点击开始 ===');
                    console.log('仓库ID:', formData.warehouseId);
                    console.log('表单数据:', formData);

                    if (!formData.warehouseId) {
                        console.log('未选择仓库，显示提示');
                        showSelectWarehouseTip.value = true;
                        setTimeout(() => showSelectWarehouseTip.value = false, 3000);
                        ElMessage.warning('请先选择仓库');
                        return;
                    }

                    console.log('设置导入数据，打开对话框');
                    importData.value.warehouseId = formData.warehouseId;
                    importDialogVisible.value = true;
                    console.log('=== 导入按钮点击结束 ===');
                };

                // 下载导入模板
                const downloadTemplate = () => window.location.href = '/WhStockTake/DownloadInventoryTemplate';

                // 导入文件变化处理
                const handleImportFileChange = (file, fileList) => {
                    console.log('文件选择变化:', file, fileList);
                    importFileList.value = fileList;

                    // 文件大小验证
                    if (file.size > 2 * 1024 * 1024) {
                        ElMessage.error('文件大小不能超过2MB');
                        importFileList.value = [];
                        return false;
                    }

                    // 文件类型验证
                    const isExcel = file.name.endsWith('.xls') || file.name.endsWith('.xlsx');
                    if (!isExcel) {
                        ElMessage.error('只能上传Excel文件!');
                        importFileList.value = [];
                        return false;
                    }

                    return true;
                };

                // 提交导入
                const submitImport = () => {
                    console.log('确定导入，文件列表:', importFileList.value);
                    if (importFileList.value.length === 0) {
                        ElMessage.warning('请先选择Excel文件');
                        return;
                    }

                    importLoading.value = true;

                    // 手动创建 FormData 并发送请求
                    const formDataObj = new FormData();
                    formDataObj.append('file', importFileList.value[0].raw);
                    formDataObj.append('warehouseId', importData.value.warehouseId);

                    axios.post('/WhStockTake/ImportInventoryItems', formDataObj, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    }).then(response => {
                        handleImportSuccess(response.data);
                    }).catch(error => {
                        handleImportError(error);
                    });
                };

                // 导入成功处理
                const handleImportSuccess = (response) => {
                    importLoading.value = false;
                    console.log('导入响应:', response);

                    if (response.code === 200) {
                        if (response.data && response.data.length > 0) {
                            // 添加到现有盘点明细中
                            inventoryItems.value = [...inventoryItems.value, ...response.data];
                            ElMessage.success(`导入成功，共导入 ${response.data.length} 条数据`);
                        } else {
                            ElMessage.success('导入成功，但未发现有效数据');
                        }
                        importDialogVisible.value = false;
                        importFileList.value = []; // 清空文件列表
                    } else {
                        ElMessage.error(response.msg || '导入失败');
                    }
                };

                // 导入失败处理
                const handleImportError = (error) => {
                    importLoading.value = false;
                    console.error('导入错误:', error);
                    ElMessage.error('导入失败，请重试或检查文件格式');
                };

                // 上传前检查
                const beforeImportUpload = (file) => {
                    console.log('上传前检查:', file);
                    const isExcel = file.name.endsWith('.xls') || file.name.endsWith('.xlsx');
                    const isLt2M = file.size / 1024 / 1024 < 2;

                    if (!isExcel) {
                        ElMessage.error('只能上传Excel文件!');
                        return false;
                    }
                    if (!isLt2M) {
                        ElMessage.error('上传文件大小不能超过 2MB!');
                        return false;
                    }

                    return true;
                };

                // 导入对话框关闭处理
                const handleImportDialogClosed = () => {
                    importFileList.value = [];
                    importLoading.value = false;
                };

                // 文件变化处理
                const handleFileChange = (file, fileList) => {
                    if (file.size > 200 * 1024 * 1024) {
                        ElMessage.error('文件大小不能超过200MB');
                        fileList.value = fileList.value.filter(f => f.uid !== file.uid);
                    }
                };

                // 显示自定义字段设置
                const showCustomFieldSetting = () => ElMessage.info('自定义字段设置功能待实现');
                // 关闭页面
                const handleClose = () => { buttonLoading.close = true; window.history.back(); };

                // 保存为草稿（改进版）
                const handleSaveAsDraft = async () => {
                    const requiredFields = [
                        { name: '盘点类型', valid: !!formData.inventoryType },
                        { name: '仓库名称', valid: formData.warehouseId !== null },
                        { name: '经办人', valid: formData.operatorBy !== null },
                        { name: '盘点开始时间', valid: !!formData.inventoryStartTime }
                    ];
                    const missing = requiredFields.filter(f => !f.valid).map(f => f.name);
                    if (missing.length > 0) {
                        ElMessage.warning(`请完善以下信息：${missing.join('、')}`);
                        return;
                    }

                    buttonLoading.saveAsDraft = true;
                    try {
                        // 清除旧草稿
                        localStorage.removeItem('inventoryDraft');

                        const draft = {
                            formData: toRaw(formData),
                            customFields: toRaw(customFields),
                            inventoryItems: toRaw(inventoryItems.value),
                            fileList: fileList.value.map(f => ({
                                name: f.name,
                                url: f.url,
                                status: f.status,
                                uid: f.uid
                            })),
                            saveTime: new Date().toLocaleString('zh-CN', {
                                year: 'numeric',
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit'
                            })
                        };

                        localStorage.setItem('inventoryDraft', JSON.stringify(draft));

                        // 显示成功消息，包含保存时间
                        ElMessage.success({
                            message: `草稿保存成功！保存时间：${draft.saveTime}`,
                            duration: 3000,
                            showClose: true
                        });

                        // 模拟供应商编辑页面的效果 - 添加轻微动画效果
                        const saveBtn = document.querySelector('.el-button--success');
                        if (saveBtn) {
                            saveBtn.classList.add('saved-animation');
                            setTimeout(() => {
                                saveBtn.classList.remove('saved-animation');
                            }, 1000);
                        }

                    } catch (error) {
                        console.error('保存草稿失败:', error);
                        ElMessage.error('保存失败，请重试');
                    } finally {
                        buttonLoading.saveAsDraft = false;
                    }
                };

                // 保存盘点单 - 修复版本（确保请求正确发送）
                const handleSave = async () => {
                    const hasEmpty = inventoryItems.value.some(item => !item.goodsCode);
                    if (hasEmpty) {
                        showSelectGoodsTip.value = true;
                        setTimeout(() => showSelectGoodsTip.value = false, 3000);
                        return;
                    }

                    const required = [
                        { name: '盘点类型', valid: !!formData.inventoryType },
                        { name: '仓库名称', valid: formData.warehouseId !== null },
                        { name: '经办人', valid: formData.operatorBy !== null },
                        { name: '盘点开始时间', valid: !!formData.inventoryStartTime },
                        { name: '盘点明细', valid: inventoryItems.value.length > 0 }
                    ];
                    const missing = required.filter(f => !f.valid).map(f => f.name);
                    if (missing.length > 0) {
                        ElMessage.warning(`请完善以下信息：${missing.join('、')}`);
                        return;
                    }

                    buttonLoading.save = true;
                    try {
                        const now = new Date();

                        // 修复日期格式问题 - 使用字符串格式而不是 ISO 格式
                        const formatDateForBackend = (dateValue) => {
                            if (!dateValue) {
                                const now = new Date();
                                return now.toISOString().slice(0, 19); // 生成 "2025-11-05T20:31:36" 格式
                            }
                            // 若为字符串，尝试转换为Date对象后再格式化
                            const date = new Date(dateValue);
                            if (isNaN(date.getTime())) {
                                const now = new Date();
                                return now.toISOString().slice(0, 19);
                            }
                            return date.toISOString().slice(0, 19);
                        };

                        // 构建提交数据 - 使用更简单的格式
                        const submitData = {
                            StockTake: {
                                inventoryOrderId: formData.inventoryOrderId || 0,
                                inventoryOrderNo: formData.inventoryOrderNo || '',
                                inventoryType: formData.inventoryType || '',
                                inventoryStartTime: formatDateForBackend(formData.inventoryStartTime),
                                inventoryEndTime: formatDateForBackend(formData.inventoryEndTime),
                                warehouseId: Number(formData.warehouseId),
                                operatorBy: Number(formData.operatorBy),
                                sourceOrderNo: formData.sourceOrderNo || "",
                                inbound: formData.inbound || "N",
                                outbound: formData.outbound || "N",
                                orderStatus: formData.orderStatus || "0",
                                auditorComment: formData.auditorComment || "",
                                createBy: Number(formData.createBy) || 1,
                                createTime: formatDateForBackend(now),
                                updateBy: Number(formData.updateBy) || 1,
                                updateTime: formatDateForBackend(now),
                                operatorDate: formatDateForBackend(now),
                                auditorBy: Number(formData.auditorBy) || 0,
                                auditorTime: formatDateForBackend(now)
                            },
                            StockTakeDetails: inventoryItems.value.map(item => ({
                                inventoryOrderDetailId: item.inventoryOrderDetailId || 0,
                                inventoryOrderId: 0,
                                goodsCode: item.goodsCode || '',
                                productUnit: item.productUnit || "件",
                                bookInventory: Number(item.bookInventory) || 0,
                                storageLocationId: Number(item.storageLocationId) || 0,
                                inventoryQuantity: Number(item.inventoryQuantity) || 0,
                                profitLossQuantity: Number(item.profitLossQuantity) || 0,
                                referenceUnitPrice: Number(item.referenceUnitPrice) || 0,
                                profitLossAmount: Number(item.profitLossAmount) || 0,
                                isDelete: item.isDelete || 'N',
                                remarks: item.remarks || '',
                                createBy: Number(item.createBy) || Number(formData.createBy) || 1,
                                createTime: formatDateForBackend(now),
                                updateBy: Number(item.updateBy) || Number(formData.updateBy) || 1,
                                updateTime: formatDateForBackend(now),
                                attachmentId: Number(item.attachmentId) || 0
                            }))
                        };

                        console.log('提交的数据:', JSON.stringify(submitData, null, 2));

                        // 直接发送创建请求
                        console.log('发送创建请求...');
                        const res = await axios.post('/WhStockTake/Create', submitData, {
                            headers: {
                                'Content-Type': 'application/json',
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            timeout: 30000
                        });

                        console.log('创建请求响应:', res.data);

                        if (res.data.code === 200) {
                            ElMessage.success('盘点单保存成功！');
                            localStorage.removeItem('inventoryDraft');
                            // 延迟跳转，确保用户看到成功消息
                            setTimeout(() => {
                                window.location.href = '/WhStockTake/Index';
                            }, 1500);
                        } else {
                            ElMessage.error(res.data.msg || '保存失败');
                        }
                    } catch (error) {
                        console.error('保存错误:', error);
                        if (error.response) {
                            console.error('响应数据:', error.response.data);
                            console.error('响应状态:', error.response.status);
                            ElMessage.error(error.response.data?.msg || `请求失败: ${error.response.status}`);
                        } else if (error.request) {
                            console.error('请求数据:', error.request);
                            ElMessage.error('网络错误，请检查网络连接');
                        } else {
                            ElMessage.error(`请求错误: ${error.message}`);
                        }
                    } finally {
                        buttonLoading.save = false;
                    }
                };

                // 前往添加仓库
                const handleGoAddWarehouse = () => window.location.href = '/BiWarehouse/Create';
                // 前往锁定仓库
                const handleGoLockWarehouse = () => window.location.href = '/BiWarehouse/Index';
                // 部门点击处理
                const handleDepartmentClick = (data) => { selectedDepartment.value = data; loadUsersByDepartment(data.id); };

                // 用户选择处理
                const handleUserSelect = (row) => {
                    const exist = selectedUsers.value.some(u => u.id === row.id);
                    selectedUsers.value = exist ? selectedUsers.value.filter(u => u.id !== row.id) : [row];
                };

                // 移除选中用户
                const removeSelectedUser = (user) => selectedUsers.value = selectedUsers.value.filter(u => u.id !== user.id);
                // 确认选择用户
                const confirmUserSelection = () => {
                    if (selectedUsers.value.length === 0) { ElMessage.warning('请选择经办人'); return; }
                    const user = selectedUsers.value[0];
                    formData.operatorBy = user.id;
                    operatorName.value = user.name;
                    userDialogVisible.value = false;
                    selectedUsers.value = [];
                };

                // 显示用户选择对话框
                const showUserDialog = async () => {
                    try {
                        const res = await axios.get('/WhStockTake/GetDepartmentTree');
                        departmentTree.value = res.data.data || [];
                        if (departmentTree.value.length > 0) {
                            setTimeout(() => {
                                departmentTreeRef.value?.setCurrentKey(departmentTree.value[0].id);
                                selectedDepartment.value = departmentTree.value[0];
                                loadUsersByDepartment(departmentTree.value[0].id);
                            }, 100);
                        }
                        userDialogVisible.value = true;
                    } catch (error) {
                        ElMessage.error(`加载部门数据异常：${error.message}`);
                        userDialogVisible.value = true;
                    }
                };

                // 部门搜索
                const deptSearch = ref('');
                // 用户搜索
                const userSearch = ref('');
                // 选中用户列表
                const selectedUsers = ref([]);
                // 筛选后用户列表
                const filteredUserList = computed(() => {
                    if (!userSearch.value) return userList.value;
                    return userList.value.filter(u => u.name.includes(userSearch.value) || u.department.includes(userSearch.value));
                });

                // 过滤部门
                const filterDept = (value, data) => !deptSearch.value || data.name.includes(deptSearch.value);
                // 用户行样式
                const userRowClass = ({ row }) => selectedUsers.value.some(u => u.id === row.id) ? 'user-selected' : '';
                // 监听部门搜索
                watch(deptSearch, () => departmentTreeRef.value?.filter(deptSearch.value));

                // 商品查询
                const searchGoods = async () => {
                    console.log("仓库ID:", formData.warehouseId);
                    console.log("库位ID:", selectedLocationId.value);
                    if (!formData.warehouseId) {
                        ElMessage.warning('请先选择仓库');
                        return;
                    }

                    loadingGoods.value = true;
                    try {
                        const res = await axios.get('/WhStockTake/GetGoodsByWarehouseAndLocation', {
                            params: {
                                warehouseId: formData.warehouseId,
                                storageLocationId: selectedLocationId.value
                            }
                        });
                        if (res.data.code === 200) {
                            selectableGoodsList.value = res.data.data || [];
                            if (selectableGoodsList.value.length === 0) {
                                ElMessage.info('当前仓库+库位下暂无商品数据');
                            }
                        } else {
                            ElMessage.warning(res.data.msg || '查询商品失败');
                            selectableGoodsList.value = [];
                        }
                    } catch (error) {
                        ElMessage.error(`查询异常：${error.message}`);
                        selectableGoodsList.value = [];
                    } finally {
                        loadingGoods.value = false;
                    }
                };

                // 重置商品搜索
                const resetGoodsSearch = () => {
                    goodsSearch.value = '';
                    // 重新加载所有商品数据
                    searchGoods();
                };

                // 打开添加货品模态框
                const handleAddItem = () => {
                    if (!formData.warehouseId) {
                        showSelectWarehouseTip.value = true;
                        setTimeout(() => showSelectWarehouseTip.value = false, 3000);
                        return;
                    }
                    showSelectWarehouseTip.value = false;
                    isAddGoodsDialogOpen.value = true;
                    goodsSearch.value = '';
                    selectedLocationId.value = null;
                    selectableGoodsList.value = [];
                    selectedGoodsList.value = [];
                    addGoodsDialogVisible.value = true;

                    if (locationList.value.length > 0) {
                        selectedLocationId.value = locationList.value[0].id;
                        searchGoods();
                    } else {
                        axios.get(`/WhStockTake/GetWarehouseLocations?warehouseId=${formData.warehouseId}`)
                            .then(res => {
                                if (res.data.code === 200) {
                                    locationList.value = res.data.data || [];
                                    if (locationList.value.length > 0) {
                                        selectedLocationId.value = locationList.value[0].id;
                                        searchGoods();
                                    } else {
                                        ElMessage.warning('当前仓库下无可用库位，请先添加库位');
                                    }
                                }
                            });
                    }
                };

                // 新增：获取账面库存
        const getBookInventory = async (goodsId, warehouseId, storageLocationId) => {
            try {
                const res = await axios.get('/WhStockTake/GetBookInventory', {
                    params: { warehouseId, goodsId, storageLocationId }
                });
                return res.data.code === 200 ? res.data.data : 0;
            } catch (error) {
                ElMessage.error('获取账面库存失败，请重试');
                return 0;
            }
        };

                // 监听库位变化，更新已添加商品的账面库存
                const handleLocationChange = async (index, row) => {
                    console.log(`库位变化: 行${index}, 商品${row.goodsName}, 新库位${row.storageLocationId}`);

                    // 保存当前库位（用于回退）
                    const originalLocationId = row.originalStorageLocationId || row.storageLocationId;

                    if (!row.storageLocationId || !formData.warehouseId || !row.goodsId) {
                        console.warn('缺少必要参数，无法更新账面库存');
                        return;
                    }

                    try {
                        // 显示加载状态
                        row.updatingBookInventory = true;

                        // 获取新库位的账面库存
                        const bookInventory = await getBookInventory(
                            row.goodsId,
                            formData.warehouseId,
                            row.storageLocationId
                        );

                        console.log(`商品 ${row.goodsName} 在新库位 ${row.storageLocationId} 的账面库存:`, bookInventory);

                        // 核心判断：无库存则提示并回退
                        if (Number(bookInventory) <= 0) {
                            ElMessage.warning(`当前库位下无账面库存，已自动回退原库位`);

                            // 使用Vue.nextTick确保DOM更新
                            await nextTick();

                            // 回退到原库位（更新下拉框值）
                            row.storageLocationId = originalLocationId;

                            // 重新获取原库位的库存并更新
                            const originalBookInventory = await getBookInventory(
                                row.goodsId,
                                formData.warehouseId,
                                originalLocationId
                            );
                            row.bookInventory = originalBookInventory;
                            calculateDiff(index); // 重新计算原库位的盈亏

                            // 保存原库位ID，以备下次使用
                            row.originalStorageLocationId = originalLocationId;
                        } else {
                            // 有库存则正常更新
                            row.bookInventory = bookInventory;
                            calculateDiff(index); // 计算新库位的盈亏
                            // 更新原库位记录
                            row.originalStorageLocationId = row.storageLocationId;
                            ElMessage.success(`已更新 ${row.goodsName} 的账面库存`);
                        }
                    } catch (error) {
                        console.error('更新账面库存失败:', error);
                        ElMessage.error('更新库存失败，已回退原库位');
                        // 异常时也回退原库位
                        row.storageLocationId = originalLocationId;
                    } finally {
                        row.updatingBookInventory = false;
                    }
                };

                // 批量更新所有商品的账面库存（当切换主库位时）
                const updateAllBookInventory = async () => {
                    if (!selectedLocationId.value || !formData.warehouseId) {
                        return;
                    }

                    try {
                        const loading = ElLoading.service({
                            target: document.querySelector('.el-table'),
                            text: '正在更新所有商品账面库存...'
                        });

                        // 遍历所有盘点明细，更新账面库存
                        for (let i = 0; i < inventoryItems.value.length; i++) {
                            const item = inventoryItems.value[i];
                            if (item.goodsId && item.storageLocationId) {
                                const bookInventory = await getBookInventory(
                                    item.goodsId,
                                    formData.warehouseId,
                                    item.storageLocationId
                                );
                                item.bookInventory = bookInventory;
                                calculateDiff(i);
                            }
                        }

                        loading.close();
                        ElMessage.success('已更新所有商品的账面库存');
                    } catch (error) {
                        console.error('批量更新账面库存失败:', error);
                        ElMessage.error('批量更新账面库存失败');
                    }
                };

                // 确认添加商品 - 完善版本
                const confirmAddGoods = async () => {
                    if (selectedGoodsList.value.length === 0) {
                        ElMessage.warning('请选择至少一个货品');
                        return;
                    }

                    try {
                        const loading = ElLoading.service({
                            target: document.querySelector('.el-table'),
                            text: '正在添加商品并获取库存...'
                        });

                        // 批量添加商品，并获取每个商品的账面库存
                        for (const goods of selectedGoodsList.value) {
                            // 检查是否已存在相同商品
                            const exists = inventoryItems.value.some(item =>
                                item.goodsId === goods.goodsId &&
                                item.storageLocationId === selectedLocationId.value
                            );

                            if (exists) {
                                ElMessage.warning(`商品 ${goods.goodsName} 已存在，跳过添加`);
                                continue;
                            }

                            // 获取实时账面库存
                            const bookInventory = await getBookInventory(
                                goods.goodsId,
                                formData.warehouseId,
                                selectedLocationId.value
                            );

                            console.log(`货品 ${goods.goodsName} 的账面库存:`, bookInventory);

                            // 创建新的盘点明细项
                            const newItem = {
                                inventoryOrderDetailId: 0,
                                inventoryOrderId: 0,
                                goodsId: goods.goodsId,
                                goodsCode: goods.goodsCode,
                                goodsName: goods.goodsName,
                                specification: goods.specification,
                                goodsType: goods.goodsType || '',
                                bookInventory: Number(bookInventory) || 0,
                                referenceUnitPrice: Number(goods.unitPrice) || 0,
                                storageLocationId: Number(selectedLocationId.value) || 0,
                                // 关键修复：在添加时就记录原始库位
                                originalStorageLocationId: Number(selectedLocationId.value) || 0,
                                inventoryQuantity: 0,
                                profitLossQuantity: 0,
                                profitLossAmount: 0,
                                isDelete: 'N',
                                remarks: '',
                                updatingBookInventory: false // 用于加载状态
                            };

                            // 计算初始盈亏
                            calculateDiffForNewItem(newItem);

                            inventoryItems.value.push(newItem);
                        }

                        loading.close();
                        addGoodsDialogVisible.value = false;
                        ElMessage.success(`成功添加 ${selectedGoodsList.value.length} 个货品`);

                        // 清空选中列表
                        selectedGoodsList.value = [];

                    } catch (error) {
                        console.error('添加商品失败:', error);
                        ElMessage.error('添加商品失败，请重试');
                    }
                };

                // 为新商品计算盈亏
                const calculateDiffForNewItem = (item) => {
                    const inventoryQty = Number(item.inventoryQuantity) || 0;
                    const bookQty = Number(item.bookInventory) || 0;
                    const unitPrice = Number(item.referenceUnitPrice) || 0;

                    item.profitLossQuantity = inventoryQty - bookQty;
                    item.profitLossAmount = item.profitLossQuantity * unitPrice;
                };
                // 商品选择变化处理
                const handleGoodsSelectionChange = (val) => {
                    console.log('商品选择变化:', val);
                    selectedGoodsList.value = val;
                };

                // 商品行样式
                const tableRowClassName = ({ row }) => row.isNew ? 'new-row' : '';

                // 页码变化处理
                const handlePageChange = (page) => currentPage.value = page;
                // 页面初始化
                onMounted(async () => {
                    try {
                        await loadDictData();
                        await loadBasicData();
                        await initForm();
                        setTimeout(() => basicForm.value?.clearValidate(), 1000);

                        // 移除默认测试数据，保持盘点明细为空
                    } catch (error) {
                        ElMessage.error('页面加载失败，请刷新重试');
                    }
                });

                return {
                    formData, operatorName, showWarehouseWarning, showSelectWarehouseTip, showSelectGoodsTip,
                    customFields, fileList, uploadLoading, inventoryTypeList, warehouseList, locationList,
                    userList, selectedRows, inventoryItems, total, basicForm, inventoryTable,
                    buttonLoading, basicRules, userDialogVisible, departmentTree, departmentProps,
                    selectedDepartment, departmentTreeRef, addGoodsDialogVisible, goodsSearch,
                    selectableGoodsList, selectedGoodsList, currentPage, selectedLocationId, loadingGoods,
                    deptSearch, userSearch, selectedUsers, filteredUserList,
                    importDialogVisible, importLoading, importFileList, importHeaders, importData,
                    debugMode, showDraftDialog, draftSaveTime, filteredGoodsList,

                    // 所有方法都需要在这里返回
                    generateInventoryNo, loadDictData, loadUsersByDepartment, loadBasicData,
                    checkWarehouseLockStatus, initForm, handleWarehouseChange, calculateDiff,
                    calculateProfitLossAmount, calculateBookAmount, formatQuantity, formatTotalQuantity,
                    getProfitLossType, getProfitLossText, handleAddItem, handleRemoveItem,
                    handleDeleteSelected, handleImport, downloadTemplate, beforeImportUpload,
                    submitImport, handleImportSuccess, handleImportError, handleFileChange,
                    showCustomFieldSetting, handleClose, handleSaveAsDraft, handleSave,
                    handleGoAddWarehouse, handleGoLockWarehouse, handleDepartmentClick,
                    handleUserSelect, removeSelectedUser, confirmUserSelection, showUserDialog,
                    filterDept, userRowClass, searchGoods, resetGoodsSearch,

                    handleGoodsSelectionChange, confirmAddGoods, tableRowClassName, handlePageChange,
                    handleImportFileChange, handleImportDialogClosed, handleLoadDraft, handleDiscardDraft,
                    handleSelectionChange, handleLocationChange, updateAllBookInventory, getBookInventory,
                    calculateDiffForNewItem
                };
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>